package com.eatme.web.app.coupon.template.service.impl;

import com.eatme.web.app.coupon.common.exception.AppException;
import com.eatme.web.app.coupon.template.dao.CouponTemplateDao;
import com.eatme.web.app.coupon.template.entity.CouponTemplate;
import com.eatme.web.app.coupon.template.service.IAsyncService;
import com.eatme.web.app.coupon.template.service.IBuildTemplateService;
import com.eatme.web.app.coupon.template.vo.CouponTemplateRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 构建优惠券模版接口实现
 */
@Service
public class BuildTemplateServiceImpl implements IBuildTemplateService {

    /** 异步服务 */
    private final IAsyncService asyncService;

    /** couponTemplateDao */
    private final CouponTemplateDao couponTemplateDao;

    @Autowired
    public BuildTemplateServiceImpl(IAsyncService asyncService, CouponTemplateDao couponTemplateDao) {
        this.asyncService = asyncService;
        this.couponTemplateDao = couponTemplateDao;
    }

    /**
     * 创建优惠券模板
     *
     * @param request {@link CouponTemplateRequest} 模板信息请求对象
     * @return {@link  CouponTemplate} 优惠券模板实体
     * @throws AppException
     */
    @Override
    public CouponTemplate buildTemplate(CouponTemplateRequest request) throws AppException {

        // 参数合法性校验
        if (!request.validate())
            throw new AppException("BuildTemplate Param Is Not Valid!");

        // 判断同名的优惠券模版是否存在
        if (null != couponTemplateDao.findByName(request.getName())) {
            throw new AppException("Exist Same Name Template!");
        }
        // 构造 CouponTemplate 并保存到数据库中
        CouponTemplate template = requestToTemplate(request);
        template = couponTemplateDao.save(template);

        // 根据优惠券模版异步生成优惠券码
        asyncService.asyncConstructCouponByTemplate(template);

        return template;
    }

    /**
     * 将TemplateRequest 转换为 CouponTemplate
     * @param request
     * @return
     */
    private CouponTemplate requestToTemplate(CouponTemplateRequest request) {
        return new CouponTemplate(
                request.getName(),
                request.getLogo(),
                request.getDesc(),
                request.getCategory(),
                request.getProductLine(),
                request.getCount(),
                request.getUserId(),
                request.getTarget(),
                request.getRule()
                );
    }


}
